<template>
  <view>

      <view class="box" style="padding-bottom: 10rpx">
        <view class="box-sel">
          <view
              @click="dtuSelect('all')"
              :class="dtuSelected=='all'?'box-sel-item box-sel-item-selected':'box-sel-item'">全部</view>
          <view
              @click="dtuSelect('good')"
              :class="dtuSelected=='good'?'box-sel-item box-sel-item-selected':'box-sel-item'">良好</view>
          <view
              @click="dtuSelect('bad')"
              :class="dtuSelected=='bad'?'box-sel-item box-sel-item-selected':'box-sel-item'">故障</view>
        </view>
      </view>
      <view class="box">

        <view class="box-input">
          <u-row>
            <u-col :span="1">
              <u-icon name="search" size="40rpx"></u-icon>
            </u-col>
            <u-col :span="11">
              <input placeholder="输入地点、备注、查询" border-style="none"></input>
            </u-col>
          </u-row>
        </view>
      </view>

      <!-- 电影列表 -->
      <view class="box" style="background-color: rgba(0,0,0,0);">
        <view style="height: 20rpx"></view>
        <view class="movie-box" v-for="(item, index ) in dtuData" :key="index">
          <view>
                <view style="font-size: 26rpx;color: #666666">IMEI：{{item.imei}}</view>
          </view>
          <view style="height: 10rpx"></view>
          <u-row>
            <u-col :span="3">
              <image :src="$kt.file.byPath('image/defaultShow.png')"
                     mode="aspectFill"
                     class="movie-box-img"></image>
            </u-col>
            <u-col :span="8.5">
              <view style="padding: 10rpx;vertical-align: top;padding: 0 0 0 20rpx;box-sizing: border-box">
                <view style="font-size: 32rpx;color: #000000;">测试的DTU
                  <view style="width: 150rpx;float: right;">
                    <u-tag
                        size="mini"
                        text="状态：良好" type="success" />
                  </view>
                </view>
                <view style="height: 5rpx"></view>
                <view style="color: #666666;font-size: 26rpx">
                  <view>使用时间：{{item.time}}</view>
                  <view style="height: 10rpx"></view>
                  <view>合闸状态：合闸</view>
                  <view style="height: 10rpx"></view>
                  <view
                  style="border-top: 1rpx solid #999;padding: 10rpx 0 10rpx 0;"
                  >
                    <u-row >
                      <u-col :span="6">
                        <view >
                          电压01:{{ mqttData.get(item.imei).voltage01.toFixed(2) }}V
                        </view>
                      </u-col>
                      <u-col :span="6">
                        <view>
                          电压02:{{ mqttData.get(item.imei).voltage02.toFixed(2) }}V
                        </view>
                      </u-col>

                    </u-row>

                    <u-row>
                      <u-col :span="6">
                          <view>
                            频率01:{{mqttData.get(item.imei).frequency01.toFixed(2)}}F
                          </view>
                      </u-col>
                      <u-col :span="6">
                          <view>
                            电流01:{{(mqttData.get(item.imei).electricCurrent01 * 100).toFixed(4)}}mA
                          </view>
                      </u-col>
                    </u-row>
                  </view>

                  <view style="height: 10rpx"></view>
                </view>
              </view>
            </u-col>

          </u-row>
          <view style="height: 10rpx"></view>
          <view
          @click="openMap()"
          >
            <u-row>
              <u-col :span="1">
                <u-icon name="map-fill" size="40rpx"></u-icon>
              </u-col>
              <u-col :span="11">
                <view style="font-size: 26rpx;color: #666666">{{item.location}}</view>
              </u-col>
            </u-row>
          </view>
        </view>
      </view>


    <view style="height: 120rpx"></view>

  </view>
</template>

<script>
import mqtt from '@/utils/mqtt4.1.0.js';
export default {
  data() {
    return {
      serve: {
        host: '59.52.62.175',
        wsport: '8083',
        wssport:'443',
        path: '/mqtt',
      },
      onTopic: '863482060503048',
      onSub: 'topic2',
      Qos: 2,
      sendMassage: '',
      time:0,
      receiveMessage: '',
      client: null,
      //MQTT连接的配置
      options: {
        wsOptions: {},
        protocolVersion: 5, //MQTT连接协议版本
        clientId: '',
        keepalive: 60,
        clean: false,
        username: '',
        password: '',
        reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
        connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
        resubscribe: true //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
      },

      /**
       * 全部：all
       * 良好：good
       * 故障：bad
       */
      dtuSelected: 'all',
      mqttData : new Map(),
      dtuData:[
        {
          imei: '863482060503048',
          status: 'good',
          time: '一小时22分',
          location: '香港市铜锣湾区洪兴社第三社保安处',
        },
        {
          imei: '863482060503048',
          status: 'good',
          time: '一小时22分',
          location: '香港市铜锣湾区洪兴社第三社保安处',
        },
        {
          imei: '863482060483969',
          status: 'good',
          time: '一小时22分',
          location: '香港市铜锣湾区洪兴社第三社保安处',
        },
        {
          imei: '863482060503048',
          status: 'good',
          time: '一小时22分',
          location: '香港市铜锣湾区洪兴社第三社保安处',
        },
        {
          imei: '863482060483969',
          status: 'good',
          time: '一小时22分',
          location: '香港市铜锣湾区洪兴社第三社保安处',
        },
        {
          imei: '863482060503048',
          status: 'good',
          time: '一小时22分',
          location: '香港市铜锣湾区洪兴社第三社保安处',
        },{
          imei: '863482060503048',
          status: 'good',
          time: '一小时22分',
          location: '香港市铜锣湾区洪兴社第三社保安处',
        },
        {
          imei: '863482060483969',
          status: 'good',
          time: '一小时22分',
          location: '香港市铜锣湾区洪兴社第三社保安处',
        }
      ]

    };
  },
  created() {
    console.log("this.options.clientId",this.options.clientId)
    let clientId = "mqtt_" + Math.random().toString(16).substr(2, 8);

    console.log("生成的随机clientId为：" + clientId);

    this.options.clientId=clientId;
    this.connect();

  },
  methods: {
    //getMqttData
    getMqttData(imei,param){
      return this.mqttData.get(imei)?this.mqttData.get(imei)[param].toFixed(2):0;
    },
    parseHexData(msgStr) {
      var substring = msgStr.split(",")[1].substring(6);
      console.log(substring);
      var hexData = substring.replace(/\s/g, "");
      var deviceData = {};

      //imei
      deviceData.imei = msgStr.split(",")[0];

      // 电流01
      deviceData.electricCurrent01 = this.get32Float(this.extractHexSubstring(hexData, 1, 2));

      // 电流02
      deviceData.electricCurrent02 = this.get32Float(this.extractHexSubstring(hexData, 3, 4));

      // 电压01
      deviceData.voltage01 = this.get32Float(this.extractHexSubstring(hexData, 5, 6));

      // 频率01
      deviceData.frequency01 = this.get32Float(this.extractHexSubstring(hexData, 7, 8));

      // 电流03
      deviceData.electricCurrent03 = this.get32Float(this.extractHexSubstring(hexData, 9, 10));

      // 电流04
      deviceData.electricCurrent04 = this.get32Float(this.extractHexSubstring(hexData, 11, 12));

      // 电压02
      deviceData.voltage02 = this.get32Float(this.extractHexSubstring(hexData, 13, 14));

      // 频率02
      deviceData.frequency02 = this.get32Float(this.extractHexSubstring(hexData, 15, 16));

      // 过电压值
      deviceData.overVoltageValue = this.get32Float(this.extractHexSubstring(hexData, 17, 18));

      // 过电压时限
      deviceData.overVoltageTimeLimit = this.get16Long(this.extractHexSubstring(hexData, 19, 19));

      // 过电压次数
      deviceData.overVoltageCount = this.get16Long(this.extractHexSubstring(hexData, 20, 20));

      // 低电压值
      deviceData.lowVoltageValue = this.get32Float(this.extractHexSubstring(hexData, 21, 22));

      // 低电压时限
      deviceData.lowVoltageTimeLimit = this.get16Long(this.extractHexSubstring(hexData, 23, 23));

      // 低电压次数
      deviceData.lowVoltageCount = this.get16Long(this.extractHexSubstring(hexData, 24, 24));

      // 漏电流值
      deviceData.leakageCurrentValue = this.get32Float(this.extractHexSubstring(hexData, 25, 26));

      // 漏电流时限
      deviceData.leakageCurrentTimeLimit = this.get16Long(this.extractHexSubstring(hexData, 27, 27));

      // 漏电流次数
      deviceData.leakageCurrentCount = this.get16Long(this.extractHexSubstring(hexData, 28, 28));

      // 过载保护
      deviceData.overloadProtection = this.get32Float(this.extractHexSubstring(hexData, 29, 30));

      // 过载时限
      deviceData.overloadTimeLimit = this.get16Long(this.extractHexSubstring(hexData, 31, 31));

      // 过载次数
      deviceData.overloadCount = this.get16Long(this.extractHexSubstring(hexData, 32, 32));

      // 短路次数
      deviceData.shortCircuitCount = this.get16Long(this.extractHexSubstring(hexData, 33, 33));

      // 雷击次数
      deviceData.lightningStrikeCount = this.get16Long(this.extractHexSubstring(hexData, 34, 34));

      // 重合闸次数
      deviceData.closingOperationCount = this.get16Long(this.extractHexSubstring(hexData, 35, 35));

      // 保存
      deviceData.saveCount = this.get16Long(this.extractHexSubstring(hexData, 36, 36));

      // 过压合闸电压
      deviceData.overVoltageClosingVoltage = this.get32Float(this.extractHexSubstring(hexData, 37, 38));

      // 欠压合闸电压
      deviceData.underVoltageClosingVoltage = this.get32Float(this.extractHexSubstring(hexData, 39, 40));

      // 过压状态
      deviceData.overVoltageStatus = this.get16Long(this.extractHexSubstring(hexData, 41, 41));

      // 欠压状态
      deviceData.underVoltageStatus = this.get16Long(this.extractHexSubstring(hexData, 42, 42));

      // 漏电状态
      deviceData.leakageStatus = this.get16Long(this.extractHexSubstring(hexData, 43, 43));

      // 过载状态
      deviceData.overloadStatus = this.get16Long(this.extractHexSubstring(hexData, 44, 44));

      // 短路状态
      deviceData.shortCircuitStatus = this.get16Long(this.extractHexSubstring(hexData, 45, 45));

      // 重合闸动作次数
      deviceData.numberOfreclosingActions = this.get16Long(this.extractHexSubstring(hexData, 46, 46));

      // 重合闸剩余时间
      deviceData.closingOperationRemainingTime = this.get32Float(this.extractHexSubstring(hexData, 47, 48));

      // 重合闸故障复归时间
      deviceData.closingOperationFaultRecoveryTime = this.get32Float(this.extractHexSubstring(hexData, 49, 50));

      // 输出状态指示
      deviceData.outputStatusIndication = this.get16Long(this.extractHexSubstring(hexData, 51, 51));

      // 过流设定重合闸次数
      deviceData.overcurrentSettingClosingCount = this.get16Long(this.extractHexSubstring(hexData, 52, 52));

      // 过载重合闸动作次数
      deviceData.overloadClosingOperationCount = this.get16Long(this.extractHexSubstring(hexData, 53, 53));

      // 过载动作合闸倒计时
      deviceData.overloadActionClosingCountdown = this.get32Float(this.extractHexSubstring(hexData, 54, 55));

      // 过载重合闸计次复归时间
      deviceData.overloadClosingCountResetTime = this.get32Float(this.extractHexSubstring(hexData, 56, 57));

      // 总复归
      deviceData.totalReturn = this.get16Long(this.extractHexSubstring(hexData, 58, 58));

      // 雷击电
      deviceData.lightningStrikeVoltageSetting = this.get32Float(this.extractHexSubstring(hexData, 59, 60));

      // 雷击单次屏蔽时间
      deviceData.lightningStrikeSingleTimeShieldTime = this.get16Long(this.extractHexSubstring(hexData, 61, 61));

      return deviceData;
    },
    extractHexSubstring(hexData, start, end) {
      let startIndex = (start - 1) * 4;
      let endIndex = Math.min(end * 4, hexData.length);
      return hexData.substring(startIndex, endIndex);
    },
    get32Float(hexValue) {
      let intValue = parseInt(hexValue, 16);
      let buffer = new ArrayBuffer(4);
      let view = new DataView(buffer);
      view.setUint32(0, intValue);
      let floatValue = view.getFloat32(0);
      return floatValue;
    },
    get16Long(hexValue) {
      let longValue = parseInt(hexValue, 16);
      return longValue;
    },

    connect: function() {
      var hosts = '';

      // // #ifdef APP-PLUS
      //   // hosts = 'wss://' + this.serve.host + ':443/mqtt';
      //    hosts = 'tcp://IP:8083/mqtt';
      //   // #endif

      //   // #ifdef H5

      //   hosts = 'tcp://' + this.serve.host + ':1883';
      //   // hosts = 'tcp://49.234.42.125:8083/mqtt';
      //    // hosts = 'tcp://' + this.globalData.serve.host + ':' + this.globalData.serve.wsport + this.globalData.serve.path;
      //   //#endif
      //   // #ifdef MP-WEIXIN
      //   // wx仅仅可以使用体验版

      // // #endif
      hosts = 'wx://' + this.serve.host + ':8083/mqtt';
      console.log(hosts);
      console.log(hosts);
      if (this.client == null || this.client.connented == false) {
        uni.showLoading({
          title: '连接中···'
        })
        //console.log(hosts, this.options)
        this.client = mqtt.connect(
            hosts,
            this.options
        );

        this.client.on('connect', () => {
          uni.hideLoading();
          this.showToast('连接成功', 1000, 'success')
          this.subscribe(['863482060483969','863482060503048'])
          this.client.on('message', (topic, message) => {
            console.log('收到来自' + topic + '的消息' + message.toString());
            let mqttMsg = this.parseHexData(message.toString())
            console.log("mqttMsg:{}",mqttMsg);
            // 在适当的位置声明一个空 Map 对象
            this.mqttData.set(topic, mqttMsg);
            this.$set(this, 'mqttData', this.mqttData);
            console.log("mqttData:{}",this.mqttData);
          });
        });
      }

      this.client.on('reconnect', error => {
        uni.hideLoading();
        this.showToast('正在重连···', 1000)

      });
      this.client.on('error', error => {
        uni.hideLoading();
        this.showToast('连接失败!', 1000)
      });

    },
    subscribe: function(topicImei) {
      // 判断是否已成功连接
      if (!this.client || !this.client.connected) {
        this.showToast('客户端未连接', 1000)
        return;
      }

      this.client.subscribe(topicImei, {
        qos: this.Qos
      }, error => {
        if (!error) {
          this.showToast('订阅成功', 1000, 'success')
          console.log('订阅成功');
          this.client.on('message', (topic, message) => {
            if (topicImei == topic) {
              console.log('收到来自' + topic + '的消息' + message.toString());
              return this.parseHexData(message.toString())
            }
          });
        }
      });

      /* //订阅多个主题
    this.client.subscribe(['one', 'two', 'three'], { qos: 1 }, err => {
      console.log(err || '订阅成功');
      this.show(err || '订阅成功');
     });

          // 订阅不同 qos 的不同主题
          this.client.subscribe(
              [
                  { hello: 1 },
                  { 'one/two/three': 2 },
                  { '#': 0 }
              ],
              (err) => {
                this.show();console.log(err || '订阅成功')
              },
          )


    }); */
    },
    publish: function() {
      // 判断是否已成功连接
      if (!this.client || !this.client.connected) {
        this.showToast('客户端未连接', 1000)
        return;
      }
      if (this.sendMassage != '') {
        // var send = '{"code": 200, "msg": "发送打1111指令", "data": "2.doc"}';

        // 定义JSON对象
        const messageq = {
          code: 200,
          msg: '发送打印指令',
          data: '2.doc'
        }

        // 将JSON对象转换为JSON字符串
        const message1 = JSON.stringify(messageq)
        this.client.publish(this.onSub,message1, error => {
          console.log(error || '消息发布成功');
          this.showToast('消息发布成功', 1000, 'success')
        });
      } else {
        this.showToast('发布消息为空', 1000)
      }

    },
    unsubscribe: function() {
      this.client.unsubscribe(
          // topic, topic Array, topic Array-Onject
          // ['one', 'two', 'three'],
          this.onTopic,
          err => {
            console.log(err || '取消订阅成功');
            this.showToast('取消订阅成功', 1000, 'success')
          }
      );
    },
    unconnect: function() {
      if (!this.client || !this.client.connected) {
        this.showToast('客户端未连接', 1000)
        return;
      }
      this.client.end();
      this.client = null
      this.showToast('成功断开连接', 1000, 'success')
      console.log('断开连接');
    },
    showToast: function(title, time, icon = 'none') {
      uni.showToast({
        title: title,
        icon: icon,
      });
      setTimeout(function() {
        uni.hideToast();
      }, time);
    },


    select(code) {
      this.mSelected = code;
    },
    dtuSelect(code) {
      console.log(code);
      this.dtuSelected = code;
    },
    openMap(){
      let latitude = 28.682892;
      let longitude = 115.858198;
      uni.openLocation({
        latitude: latitude,
        longitude: longitude,
        scale: 18,
        name: '南昌市西湖区xxx路xxx小区保安处',
        address: '南昌市西湖区xxx路xxx小区保安处'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.m-box {
  background-color: #fff;
  margin: 0;
  padding: 0;
  display: inline-block;

  .m {
    display: inline-block;
    font-size: 32rpx;
    color: #333;
    width: 50%;
    padding: 10rpx 20rpx;
    border: 1rpx solid #333;
    box-sizing: border-box;
    // 文字间距
    letter-spacing: 2rpx;
    margin: 0;
  }

  .m1 {
    border-radius: 30rpx 0 0 30rpx;
  }

  .m2 {
    border-radius: 0 30rpx 30rpx 0;
  }
}

.box {
  position: relative;
  width: 100%;
  padding: 0 30rpx 30rpx 30rpx;
  box-sizing: border-box;
  margin: 0;
  background-color: #FFFFFF;

  .location-tab {
    margin-top: 10rpx;
  }

  .box-input {
    background-color: #f0f0f0;
    padding: 20rpx;
    border-radius: 50rpx;
    font-size: 32rpx;
  }

  .box-sel{
    margin: 0;

    .box-sel-item{
      display: inline-block;
      margin: 10rpx;
      font-size: 30rpx;
      color: #333333;
    }

    .box-sel-item{
      display: inline-block;
      margin: 10rpx;
      font-size: 30rpx;
      color: #666666;
      padding: 0 0 10rpx 0;
      box-sizing: border-box;
    }
    .box-sel-item-selected{
      color: #000000;
      border-bottom: 2rpx solid #333333;
    }
  }

}

.cinema-box{
  position: relative;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
}

.movie-box{
  background-color: #fff;
  padding: 20rpx;
  margin: 0 0 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  border-radius: 20rpx;

  .movie-box-img{
    width: 100%;
    height: 220rpx;
    border-radius: 20rpx;
    vertical-align: top;
  }

  .btn{
    background-color: #f0f0f0;
    box-sizing: border-box;
    color: #333333;
    text-align: center;
    padding: 10rpx 0 10rpx 0;
    font-size: 20rpx;
  }

  .btn1{
    border-radius: 10rpx 0 0 10rpx;
    background-color: rgba(255, 0, 0, 0.2);
    color: rgba(255, 0, 0, 1);
  }

  .btn2{
    border-radius: 0 10rpx 10rpx 0;
    background-color: rgba(255, 0, 0, 1);
    color:#fff;
  }

  .btn:active{
    opacity: .8;
  }
}


.cinema-box:active{
  transform: scale(0.98);
}

</style>
